/**
 * 维护口令进群配置
 */
import type { OptionalFields } from '@gnlab/utils'
import { Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

export enum CodeRuleType {
  Exact = 0, // 精确匹配
  Fuzzy = 1, // 模糊匹配
  Regex = 2, // 正则匹配
}

export enum CodeScope {
  External = 0,
  Group = 1,
}

export interface BaseCodeRule {
  name: string // 口令规则名称
  type: CodeRuleType // 匹配类型
  keyword: string // 匹配关键词
  scope: CodeScope[] // 应用范围
  wxids: string[] // 生效的企业微信
  groups: string[] // 要加入的群（conversationId）（顺序很重要）
  queue: boolean // 是否队列加群（每次只向一个群发邀请，前一个群成员满一定人数后才向下一个群发邀请）
  queueMemberLimit: number // 开启“队列加群”时，成员满多少人向下个群发邀请
  enable: boolean // 是否启用
}

export interface CodeRule extends BaseCodeRule {
  id: number
}

interface RespCodeRule {
  Id: number
  Name: string
  RuleType: CodeRuleType
  RuleContent: string
  ApplyType: CodeScope[]
  WxIds: string[]
  Rooms: string[]
  Enable: boolean
  IsSingle?: boolean
  MemberCount?: number
}
function formatCodeRule(raw: RespCodeRule): CodeRule {
  return {
    id: raw.Id,
    name: raw.Name,
    type: raw.RuleType,
    keyword: raw.RuleContent,
    scope: raw.ApplyType,
    wxids: raw.WxIds,
    groups: raw.Rooms,
    queue: raw.IsSingle ?? false,
    queueMemberLimit: raw.MemberCount ?? 0,
    enable: raw.Enable,
  }
}

export function getEmptyBaseCodeRule(): BaseCodeRule {
  return {
    name: '',
    type: CodeRuleType.Exact,
    keyword: '',
    scope: [],
    wxids: [],
    groups: [],
    queue: false,
    queueMemberLimit: 300,
    enable: false,
  }
}

export class CodeJoinGroups extends Service<Services> {
  async load() {
    return API('/PasswordIntoRoom/GetPasswordIntoRoomConfigs', {
      formatter(data: RespCodeRule[] | null) {
        return (data ?? []).map(formatCodeRule)
      },
    })
  }

  async addOrUpdate(rule: OptionalFields<CodeRule, 'id'>) {
    return API('/PasswordIntoRoom/SavePasswordIntoRoomConfig', {
      data: {
        Id: rule.id,
        Name: rule.name,
        RuleType: rule.type,
        RuleContent: rule.keyword,
        Enable: rule.enable,
        ApplyType: rule.scope,
        WxIds: rule.wxids,
        Rooms: rule.groups,
        IsSingle: rule.queue,
        MemberCount: rule.queueMemberLimit,
      },
      formatter() {},
    })
  }

  async remove(id: number) {
    return API('/PasswordIntoRoom/RemovePasswordIntoRoomConfig', {
      data: { Id: id },
      formatter() {},
    })
  }
}
